package ua.com.minus1.lookbattle.net;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import ua.com.minus1.lookbattle.MainActivity;

import java.io.File;
import java.net.URLEncoder;

public class HttpFileCache {
    
    private File cacheDir;

    
    public HttpFileCache(Context context){
        initCacheDir(context, null);
    }

    public HttpFileCache(Context context, String folderName){
        initCacheDir(context, folderName);
    }

    private void initCacheDir(Context context, String f) {
        String folder = f == null ? "" : File.separatorChar + f;
        //Find the dir to save cached images
        if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir = new File(Environment.getExternalStorageDirectory().getName() + File.separatorChar + "Android/data/" + context.getPackageName() + folder);
        else
            cacheDir = new File(context.getCacheDir().getPath() + folder);
        if (!cacheDir.exists())
            cacheDir.mkdirs();

        File[] files = cacheDir.listFiles();
        Log.i(HttpFileCache.class.getName(), "lens of files in cache dir " + folder + ": " + files.length);
    }
    
    public File getFile(String url){
        //I identify images by hashcode. Not a perfect solution, good for the demo.
        //String filename=String.valueOf(url.hashCode());
        //Another possible solution (thanks to grantland)
        String filename = URLEncoder.encode(url);
        File f = new File(cacheDir, filename);
        return f;
    }
    
    public void clear(){
        File[] files=cacheDir.listFiles();
        if(files==null)
            return;
        for(File f:files)
            f.delete();

        //Log.i(HttpFileCache.class.getName(), "clear cache in files");
    }

}